<template>
  <div class="time">{{ formattedTime }}</div>
</template>

<script>
export default {
  props: {
    duration: {  // 直接接收倒计时秒数
      type: Number,
      required: true,
    }
  },
  data() {
    return {
      intervalId: null,
      currentDuration: 0,  // 改为currentDuration存储当前倒计时
      reminded10: false,
      reminded5: false,
      reminded2: false,
      initialized: false
    };
  },
  mounted() {
      this.currentDuration = this.duration;  // 初始化倒计时
      this.intervalId = setInterval(this.updateCountdown, 1000);
      this.initialized = true;
  },
    beforeDestroy() {
      if (this.intervalId) {
        clearInterval(this.intervalId);
      }
    },
  computed: {
    formattedTime() {
      const hours = Math.floor(this.currentDuration / 3600)
        .toString().padStart(2, '0');
      const minutes = Math.floor((this.currentDuration % 3600) / 60)
        .toString().padStart(2, '0');
      const seconds = (this.currentDuration % 60)
        .toString().padStart(2, '0');
      return `${hours}:${minutes}:${seconds.split(".")[0].toString().padStart(2, '0')}`;
    },
  },
  methods: {
    updateCountdown() {
      if (this.currentDuration <= 0) {
        clearInterval(this.intervalId);
        this.$emit('timeup');
        return;
      }
      this.currentDuration--;
      this.checkReminders();
    },
    checkReminders() {
      const minutesLeft = Math.floor(this.currentDuration / 60);  // 改为使用currentDuration
	      const secondsLeft = this.currentDuration % 60;  // 新增秒数计算
      
      if (minutesLeft === 10 &&  secondsLeft < 2&& !this.reminded10) {
        this.$emit('reminder', '距离交卷还有10分钟');
        this.reminded10 = true;
      } else if (minutesLeft === 5 && secondsLeft < 2&&!this.reminded5) {
        this.$emit('reminder', '距离交卷还有5分钟');
        this.reminded5 = true;
      } else if (minutesLeft === 1 && secondsLeft < 2&& !this.reminded2) {
        this.$emit('reminder', '距离交卷还有2分钟');
        this.reminded2 = true;
      }
    }
},


};
</script>

<style scoped>
.time {
  font-size: 22px!important;
  color: #fff;
}
</style>
